<script setup lang="ts">
import { channel } from 'node:process';
import { computed, reactive, ref, watch } from 'vue';
import { useBoolean } from '@sa/hooks';
import { fetchAddTask, fetchGetDictMap, fetchUpdateTask } from '@/service/api';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';

defineOptions({
  name: 'TaskOperateDrawer'
});

export type OperateType = NaiveUI.TableOperateType;

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.TaskInfo | null;
}
const taskOptions = ref<CommonType.Option<string>[]>([]);

async function getTaskOptions() {
  const { error, data } = await fetchGetDictMap(['sys_task_type']);
  if (!error && Array.isArray(data.sys_task_type)) {
    taskOptions.value = data.sys_task_type as CommonType.Option<string>[];
  }
}
const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: '新增部门',
    edit: '编辑部门'
  };
  return titles[props.operateType];
});

type Model = Api.SystemManage.TaskUpdate;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: null,
    group: 'memory',
    name: '',
    remark: '',
    isActive: false,
    jobClass: '',
    jobParams: '{}',
    execStrategy: '',
    expression: '',
    startDatetime: null,
    endDatetime: null
  };
}
// 移除id和remark
type RuleKey = Extract<keyof Model, 'name' | 'isActive' | 'expression'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  isActive: defaultRequiredRule,
  expression: defaultRequiredRule
};

function handleInitModel() {
  Object.assign(model, createDefaultModel());
  console.log(props.operateType);

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  // request
  let res = null;
  if (props.operateType === 'edit') {
    res = await fetchUpdateTask(model);
  } else {
    res = await fetchAddTask(model);
  }
  const { error } = res;
  if (error) {
    return;
  }
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getTaskOptions();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="名称" path="name">
          <NInput v-model:value="model.name" placeholder="名称" />
        </NFormItem>
        <NFormItem label="存储类型" path="group" :rule="defaultRequiredRule">
          <NSelect
            v-model:value="model.group"
            :options="[
              { label: '内存', value: 'memory', type: 'option' },
              { label: 'Redis', value: 'redis', type: 'option' }
            ]"
            placeholder="请选择分组存储类型"
          />
          <NTooltip trigger="hover">
            <template #trigger>
              <NIcon :size="16" class="ml-2 cursor-help">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <circle cx="12" cy="12" r="10"></circle>
                  <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path>
                  <line x1="12" y1="17" x2="12.01" y2="17"></line>
                </svg>
              </NIcon>
            </template>
            选择内存服务时，系统重启后定时任务消息会丢失
          </NTooltip>
        </NFormItem>
        <NFormItem label="任务执行实体类" path="jobClass">
          <NInput v-model:value="model.jobClass" placeholder="任务执行实体类" />
        </NFormItem>
        <NFormItem label="参数" path="jobParams">
          <NInput v-model:value="model.jobParams" placeholder="参数" />
        </NFormItem>
        <NFormItem label="状态" path="isActive">
          <NSwitch v-model:value="model.isActive" />
        </NFormItem>
        <NFormItem label="执行表达式" path="execStrategy">
          <NSelect v-model:value="model.execStrategy" :options="taskOptions" placeholder="任务执行策略" />
        </NFormItem>
        <NFormItem label="执行表达式" path="expression">
          <NInput v-model:value="model.expression" placeholder="执行表达式" />
        </NFormItem>
        <NFormItem label="任务开始时间" path="startDatetime">
          <NInput v-model:value="model.startDatetime" placeholder="任务开始时间" />
        </NFormItem>
        <NFormItem label="任务结束时间" path="endDatetime">
          <NInput v-model:value="model.endDatetime" placeholder="任务结束时间" />
        </NFormItem>
        <NFormItem label="描述" path="remark">
          <NInput v-model:value="model.remark" placeholder="描述" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
